#ifdef SLEEP
//*********************************************************************************************/
// Defines for variables used by this userplugin
//*********************************************************************************************/

#define SLEEP_COMMAND 225

//===================================================================================================================================
// End of user configurable settings, do not change anything below this section!
//===================================================================================================================================
#include <avr/sleep.h>
#include <avr/wdt.h>

void UserPlugin_SLEEP_Command(int Par1, int Par2)
{
  if (Par1 == SLEEP_COMMAND)
    {
      // Turn off event led during sleep
      digitalWrite(13,LOW);
      sleep(Par2);
    }
}

// ************************************************************************************************************************
// Watchdog stuff from here...
// ************************************************************************************************************************

// watchdog interrupt routine
ISR (WDT_vect) 
{
   wdt_disable();  // disable watchdog
}

void sleep(byte waitCounter)
{
  
  while (waitCounter > 0) 
  {
    waitCounter--;
    wdsleep();
  }
}

void wdsleep()
{
  // disable ADC
  ADCSRA = 0;  

  // clear various "reset" flags
  MCUSR = 0;     
  // allow changes, disable reset
  WDTCSR = _BV (WDCE) | _BV (WDE);
  // set interrupt mode and an interval 
  WDTCSR = _BV (WDIE) | _BV (WDP3) | _BV (WDP0);    // set WDIE, and 8 seconds delay
  wdt_reset();  // pat the dog
  
  set_sleep_mode (SLEEP_MODE_PWR_DOWN);  
  sleep_enable();
 
  // turn off brown-out enable in software
  MCUCR = _BV (BODS) | _BV (BODSE);
  MCUCR = _BV (BODS); 
  sleep_cpu ();  
  
  // cancel sleep as a precaution
  sleep_disable();
}
#endif

